﻿using Common.Framework.Core.Foundation;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Reflection;

namespace Common.Framework.Core.FluentValidation
{
    /// <summary>
    /// 
    /// </summary>
    public static class FluentValidationConfigure
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mvcBuilder"></param>
        /// <returns></returns>
        public static IMvcBuilder AddCustomFluentValidation(this IMvcBuilder mvcBuilder)
        {
            //获得所有程序集下的验证类
            var assemblyArray = AssemblyFoundation.GetAllProjectAssemblies();

            mvcBuilder.AddFluentValidation(options =>
            {
                options.RegisterValidatorsFromAssemblies(assemblyArray);
                options.DisableDataAnnotationsValidation = true; //去掉其它的验证,只使用FluentValidation验证规则                
                options.LocalizationEnabled = true;
            });

            return mvcBuilder;
        }

        /// <summary>
        /// 关闭ModelState的默认输出
        /// </summary>
        /// <param name="services"></param>
        public static void AddSuppressModelStateInvalidFilter(this IServiceCollection services)
        {
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.SuppressModelStateInvalidFilter = true; //关闭ModelState的默认输出
            });
        }
    }
}
